package com.simple.car.loader.server.parser;

import com.simple.car.loader.server.annotation.Analysis;
import com.simple.car.loader.server.annotation.Function;
import com.simple.car.loader.server.annotation.Init;
import com.simple.car.loader.server.tools.ReflectionsTool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Function
public class AutoParser implements Parser<Object, Object> {

    private Map<Class<?>, Parser<Object, Object>> parsers;

    @Init
    public void init() throws IllegalAccessException, InstantiationException {
        Set<Class<?>> classes = ReflectionsTool.getClassByAnnotationClass(Analysis.class);
        if (classes == null || classes.isEmpty()) {
            return;
        }
        parsers = new HashMap<>();
        for (Class<?> aClass : classes) {
            Parser<Object, Object> instance = (Parser<Object, Object>) aClass.newInstance();
            parsers.put(instance.getClass(), instance);
        }
    }

    public Object parser(Object o, Class<?> clazz){
        if (o == null){
            return null;
        }
        Parser<Object, Object> parser = parsers.get(clazz);
        if (parser == null){
            throw new UnsupportedOperationException("没有解析器");
        }
        return parser.parser(o);
    }

    @Override
    public Object parser(Object o) {
        throw new UnsupportedOperationException("不支持的操作");
    }

}
